package com.buaa.singlethreadfileload.service;

import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.buaa.singlethreadfileload.bean.FileInfo;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownLoadService extends Service {
    public static final String DOWNLOAD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/";
    public static final String ACTION_START = "ACTION_START";
    public static final String ACTION_STOP = "ACTION_STOP";
    public static final String ACTION_UPDATE = "ACTION_UPDATE";
    public static final int MSG_INIT = 0;
    private DownLoadTask mTask = null;
    private String TAG = "DownloadService";


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_INIT:
                    FileInfo fileInfo = (FileInfo) msg.obj;
                    Log.i(TAG, "Init" + fileInfo);
                    //启动下载任务
                    mTask = new DownLoadTask(DownLoadService.this, fileInfo);
                    mTask.downLoad();
                    break;
                default:
                    break;
            }
        }

        ;
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //获得Activity传递过来的参数
        if (ACTION_START.equals(intent.getAction())) {
            final FileInfo fileInfo = (FileInfo) intent.getSerializableExtra("fileInfo");
            Log.i(TAG, "start:" + fileInfo.toString());
            //启动初始化线程
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    HttpURLConnection connection = null;
                    RandomAccessFile randomAccessFile = null;
                    try {
                        //连接网络文件
                        URL url = new URL(fileInfo.getUrl());
                        connection = (HttpURLConnection) url.openConnection();
                        connection.setConnectTimeout(5000);
                        connection.setRequestMethod("GET");
                        int length = -1;
                        if (connection.getResponseCode() == 200) {
                            //获得文件长度
                            length = connection.getContentLength();
                        }
                        if (length <= 0) {
                            return;
                        }
                        File dir = new File(DOWNLOAD_PATH);
                        if (!dir.exists()) {
                            dir.mkdir();
                        }
                        //在本地创建文件
                        File file = new File(dir, fileInfo.getFileName());
                        randomAccessFile = new RandomAccessFile(file, "rwd");
                        //设置文件长度
                        randomAccessFile.setLength(length);
                        fileInfo.setLength(length);
                        mHandler.obtainMessage(MSG_INIT, fileInfo).sendToTarget();

                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (connection != null) {
                            connection.disconnect();
                        }
                        if (randomAccessFile != null) {
                            try {
                                randomAccessFile.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                }
            }.start();

        } else if (ACTION_STOP.equals(intent.getAction())) {
            FileInfo fileInfo = (FileInfo) intent.getSerializableExtra("fileInfo");
            Log.i(TAG, "pause" + fileInfo.toString());
            if (mTask != null) {
                mTask.isPause = true;
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
